//
//  LiveSquareHeaderView.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/10/21.
//  Copyright © 2021 none. All rights reserved.
//

import UIKit

class LiveSquareHeaderView: UIView {
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var titles:[UIButton] = []
    // 手动触发回调
    var onTap:((Int,Int)->Void)?
    var currentIndex = 0
    
    init(titles:[String],selectedIndex:Int) {
        super.init(frame: CGRect.zero)
        currentIndex = selectedIndex
        backgroundColor = UIColor.white
        let stackView = UIStackView.init()
        stackView.spacing = 10
        stackView.alignment = .center
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        addSubview(stackView)
        stackView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(12)
        }
        
        for (index,title) in titles.enumerated() {
            let button = UIButton.init(type: .custom)
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            button.setTitleColor(Color(hex: 0xfa3c3c), for: .selected)
            button.setTitleColor(Color.lightGray, for: .normal)
            if index == currentIndex {
                button.isSelected = true
            }
            self.titles.append(button)
            button.onTap = { [weak self] (btn) in
                if let action = self?.onTap {
                    action(self?.currentIndex ?? 0,index)
                }
                self?.changeIndex(index: index)
            }
            stackView.addArrangedSubview(button)
        }
    }
    
    func changeIndex(index:Int)  {
        if self.currentIndex == index {
            return
        }
        self.titles.forEach({ (item) in
            item.isSelected = false
        })
        self.titles[index].isSelected = true
        self.currentIndex = index
    }
}
